import os
import time
import pandas as pd
from loguru import logger
import sys
from optparse import OptionParser

time_now = time.strftime("%Y%m%d-%H%M", time.localtime())
rootdir = os.path.dirname(os.path.abspath(__file__))
temp_path = f'{rootdir}/temp/{time_now}'
result_path = f'{rootdir}/results/{time_now}'


# 执行命令
def run_logparser(cmd_list):
    # 提供的日志不全时，从命令列表中移除
    log_file_name_dict = {"Security": "security",
                          "Microsoft-Windows-TerminalServices-LocalSessionManager%4Operational": "LocalSessionManager",
                          "Microsoft-Windows-TerminalServices-RemoteConnectionManager%4Operational": "RemoteConnectionManager"}
    for each_log_file_name in log_file_name_dict:
        if not os.path.exists(f"{rootdir}/data/{each_log_file_name}.evtx"):
            for cmd in cmd_list:
                if log_file_name_dict[each_log_file_name] in cmd:
                    logger.warning(f"{each_log_file_name}日志不存在,跳过此日志")
                    cmd_list.remove(cmd)

    try:
        for cmd in cmd_list:
            logger.info(f"{cmd}")
            os.system(cmd)
    except Exception as e:
        logger.error(f"run cmd error:{e}")


# 将所有结果整合到一个文件
def results_to_one_xlsx(csv_file_name_list):
    writer = pd.ExcelWriter(os.path.join(result_path, 'all_results.xlsx'))
    try:
        for csv_file_name in csv_file_name_list:
            if os.path.getsize(f'{temp_path}/{csv_file_name}'):
                data = pd.read_csv(f'{temp_path}/{csv_file_name}', encoding="gbk", index_col=0)
                data.to_excel(writer, sheet_name=csv_file_name.split(".")[0])
        writer.save()
    except Exception as e:
        logger.error(f"error:{e}")

@logger.catch
def _init():
    usage = """
    python windows_logparser.py -s "2022-12-01 01:10:00" -e "2023-01-01 12:00:00"
   
    时间格式为固定: yyyy-MM-dd hh:mm:ss
            """
    parser = OptionParser(usage=usage)
    parser.add_option('-s', '--start-time', dest='start_time', type='string', help='start time')
    parser.add_option('-e', '--end-time', dest='end_time', type='string', help='end time')
    options, args = parser.parse_args()
    start_time, end_time = options.start_time, options.end_time
    logger.remove()
    stdout_fmt = '<cyan>{time:HH:mm:ss,SSS}</cyan> ' \
                 '[<level>{level: <5}</level>] ' \
                 '<blue>{module}</blue>:<cyan>{line}</cyan> - ' \
                 '<level>{message}</level>'
    logger.add(sys.stderr, level='DEBUG', format=stdout_fmt, enqueue=True)
    dir_path_name = ['results', 'temp', temp_path, result_path]
    for each_dir in dir_path_name:
        if not os.path.exists(each_dir):
            os.mkdir(each_dir)
    from lib.all_cmd import all_cmd
    all_cmd_list = all_cmd(rootdir, temp_path, start_time, end_time)
    run_logparser(list(all_cmd_list))
    from lib.add_describe import add_description
    add_description(temp_path)
    results_to_one_xlsx(os.listdir(temp_path))


if __name__ == '__main__':
    _init()
